import { DirUtil } from "./DirUtil";
import { FileChangeUtil } from "./FileChangeUtil";
import { Md5Util } from "./Md5Util";
import { FileIoUtil } from "./FileIOUtil";

/**
 * manifest生成工具
 * @author 赵占涛
 */
export class ManifestGenUtil {
    /** 生成 */
    static gen(path: string, gateUrl: string, cdnUrl: string, version: string, manifestPath: string, versionPath: string, cb: (fileMd5: { [key: string]: { md5: string } }) => void) {
        this.getAllMd5(path, (fileMd5) => {
            let fileObj = {
                packageUrl: cdnUrl,
                remoteManifestUrl: gateUrl + "project.manifest",
                remoteVersionUrl: gateUrl + "version.manifest",
                version: version,
                engineVersion: "3.x dev",
                searchPaths: [],
                assets: {}
            };
            if (versionPath) {
                FileIoUtil.writeFile(versionPath, JSON.stringify(fileObj, undefined, 4), ()=>{
                    fileObj.assets = fileMd5;
                    delete fileObj.remoteManifestUrl;
                    FileIoUtil.writeFile(manifestPath, JSON.stringify(fileObj, undefined, 4), ()=>{
                        cb(fileMd5);
                    });
                });
            } else {
                fileObj.assets = fileMd5;
                delete fileObj.remoteManifestUrl;
                FileIoUtil.writeFile(manifestPath, JSON.stringify(fileObj, undefined, 4), ()=>{
                    cb(fileMd5);
                });
            }
        })
    }
    private static getAllMd5(path: string, cb: (fileMd5: { [key: string]: { md5: string } }) => void) {
        let fileList = this.getAllFile(path);
        let fileMd5: { [key: string]: { md5: string } } = {};
        let calcedCount = 0;
        for (let i = 0; i < fileList.length; i++) {
            const file = fileList[i];
            Md5Util.fileMd5CalcWithName(path + file, (md5: string) => {
                fileMd5[file] = { md5: md5 };
                calcedCount++;
                if (calcedCount == fileList.length) {
                    cb(fileMd5);
                }
            })
        }
    }
    private static getAllFile(path: string) {
        let fileListAll = DirUtil.getAllFile(path);
        let fileList: string[] = [];
        for (let i = 0; i < fileListAll.length; i++) {
            const file = fileListAll[i];
            if (file.startsWith("res/") || file.startsWith("src/")) {
                fileList.push(file);
            }
        }
        return fileList;
    }
}